"""
数据库配置模块
用于配置SQLAlchemy连接MySQL数据库
"""
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pydantic_settings import BaseSettings
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


class DatabaseSettings(BaseSettings):
    """数据库配置类"""
    # 从环境变量获取数据库配置，如果没有则使用默认值
    DATABASE_URL: str = "mysql+pymysql://root:myfuture@mysql:3306/openspg?charset=utf8mb4"
    
    class Config:
        env_file = ".env"
        extra = 'allow'


# 创建数据库配置实例
settings = DatabaseSettings()

# 创建数据库引擎
engine = create_engine(
    settings.DATABASE_URL,
    pool_pre_ping=True,
    pool_size=10,
    max_overflow=20
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基类
Base = declarative_base()


def get_db():
    """
    获取数据库会话的依赖函数
    用于FastAPI的依赖注入
    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()